﻿using GalaSoft.MvvmLight.Messaging;
using SubVersionOne.Message;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SubVersionOne
{
    /// <summary>
    /// Interaction logic for LoginView.xaml
    /// </summary>
    public partial class LoginView : UserControl
    {
        public VersionOneCredentials ViewModel
        {
            get
            {
                return this.DataContext as VersionOneCredentials;
            }
        }
        public LoginView()
        {
            InitializeComponent();
            this.DataContext = ViewModelLocator.MainStatic.Credentials;
        }

        private async void Login_Click(object sender, RoutedEventArgs e)
        {
            this.ViewModel.UserName = this.UserName.Text;
            this.ViewModel.Password = this.Password.Password;
            this.ViewModel.WindowsAuth = false;
            this.ViewModel.ApplicationUrl = this.VersionOneUrl.Text;
            ViewModelLocator.MainStatic.IsBusy = true;
            if (this.SavePwd.IsChecked.HasValue)
            {
                PasswordManager.Save(this.ViewModel);
            }
            
            var result = await VersionOneProxy.Login(this.ViewModel);
            if (result)
            {
                Messenger.Default.Send<LoginMessage>(new LoginMessage("Success"));
            }
            else
            {
                MessageBox.Show("Login Failed", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void Cancel_Click_1(object sender, RoutedEventArgs e)
        {

        }
    }
}
